package rs.etf.kdp.client;

import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

/**
 * Keeps jobs and their senders
 * @author Djordje Vukovic
 * @version 1.0
 * @created 18-May-2011 12:59:08 PM
 */
public class GeneralJobsManager {

	public static class Elem
	{
		private long id;
		private String identifier;
		private Sender sender;
		private String statusOnServer;
		private File writeResult;
		
		
		public Elem(long id, String identifier, Sender sender,
				String statusOnServer, File res) {
			super();
			this.id = id;
			this.identifier = identifier;
			this.sender = sender;
			this.statusOnServer = statusOnServer;
			writeResult = res;
		}


		public long getId() {
			return id;
		}


		public void setId(long id) {
			this.id = id;
		}


		public String getIdentifier() {
			return identifier;
		}


		public void setIdentifier(String identifier) {
			this.identifier = identifier;
		}


		public Sender getSender() {
			return sender;
		}


		public void setSender(Sender sender) {
			this.sender = sender;
		}


		public String getStatusOnServer() {
			return statusOnServer;
		}


		public void setStatusOnServer(String statusOnServer) {
			this.statusOnServer = statusOnServer;
		}


		public File getWriteResult() {
			return writeResult;
		}


		public void setWriteResult(File writeResult) {
			this.writeResult = writeResult;
		}
		
		
		
		
	}
	
	
	private List<Elem> sentJobs;
	String buffer;
	
	public GeneralJobsManager(){
		sentJobs = new ArrayList<Elem>();
	}
	
	public void insert(long nid, String nidentifier, Sender nsender, String nstatusOnServer, File res)
	{
		Elem newelem = new Elem(nid, nidentifier, nsender, nstatusOnServer, res);
		sentJobs.add(newelem);
	}
	
	public Sender getSenderById(long id)
	{
		for(Elem e : sentJobs)
		{
			if(e.getId()==id)
			{
				return e.getSender();
			}
		}
		return null;
	}
	
	public void remove(long remId)
	{
		for(int i=0; i<sentJobs.size(); i++)
		{
			if(sentJobs.get(i).getId() == remId)
			{
				sentJobs.remove(i);
			}
		}
	}

	public void setSentJobs(List<Elem> sentJobs) {
		this.sentJobs = sentJobs;
	}
	
	public void getCurrentStatusOnServer(long id)
	{
		String command = "status " + id;
		ObjectOutputStream out = getSenderById(id).getServerOut();
		try {
			out.writeObject(command);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Unable to send status request");
		}
		
//		synchronized(this)
//		{
//			while(buffer == null) wait();
//			String temp = buffer;
//			buffer = null;
//			return temp;
//		}
		
	}
	
	

}